/**
 * Project Name:kany-utils
 * File Name:KeyUtil.java
 * Package Name:me.kany.utils.token
 * Date:2016年9月21日下午4:57:01
 * Copyright (c) 2016, Jason.Wang All Rights Reserved.
 */
package me.kany.utils.token;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;

/**
 * ClassName:KeyUtil<br/>
 * Function: 将生成的Key文件保存到key中并返回<br/>
 * Date:2016年9月21日下午4:57:01<br/>
 * 
 * @author Jason.Wang
 * @version 1.0
 * @since JDK1.7
 * @see
 */
public class KeyUtil {

	private final static Logger logger = LoggerFactory.getLogger(KeyUtil.class.getCanonicalName());

	/**
	 * 
	 * getKey: 获取当前的Key文件. <br/>
	 *
	 * @author Jason.Wang
	 * @version 1.0
	 * @param context
	 * @return
	 * @since JDK1.7
	 *
	 */
	public static Key getKey(ServletContext context) {
		String path = (context.getRealPath("/key"));
		File file = new File(path, "key.txt");
		ObjectInputStream ois = null;
		try {
			if (!file.exists()) {
				Key key = MacProvider.generateKey(SignatureAlgorithm.HS512);
				ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(file));
				oo.writeObject(key);
				oo.close();
				return key;
			}
			ois = new ObjectInputStream(new FileInputStream(file));
			Key key = (Key) ois.readObject();
			return key;
		} catch (Exception e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
			return null;
		}finally {
			if(null != ois){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
